<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".($_GET["type"]=="add"? __("Add Category") : __("Update Category"));
$page_title=$_GET["type"]=="add"? __("Add Category") : __("Update Category");

if(!$pv["task"]["Product Categories"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage product category."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

if(!in_array($_GET["type"], array("add","edit"))){
	header("location: $this_file?type=add");
	exit();
}

if($_GET["type"]=="edit"){
	if(!$get_s["id"]){
		$errmsg=__("No category with that ID found!");
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->product_category where id='$get_d[id]'"))){
		$errmsg=__("No category with that ID found!");
	}else{
		$r_cat=mysql_fetch_assoc($r);
	}
}

if($errmsg){
	$errmsg="<h2>$page_title</h2>".format_err($errmsg);

	print format_admin_page($errmsg, $this_title);
	exit();
}

$list_cat_file=$vars["file"]["admin"]["product_category_list"];

$r_cat[0]="0";
$r_cat_d["0"]=__("None");
$cats=get_all_subcat_by_maincat();
for($i=0,$t=count($cats);$i<$t;$i++){
	$r_cat[($i+1)]=$cats[$i]["id"];
	$r_cat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
}

$td_width=180;

//#####CATEGORY POST#####
if($_POST["__req"]){
	$errmsg=verify_form_data("product_category", $post_s);
	if(!$errmsg){
		if(!in_array($post_s["parent_id"], $r_cat)){
			$errmsg.=__("Invalid parent category selected.")."<br />\n";
		}
	}

	if(!$errmsg){
		$datetime=ndate($vars["system_date_format"]);
		if($_GET["type"]=="add"){//add
			$sql="insert into $db->product_category (title, parent_id, cdate)
			values ('$post_d[_title]', '$post_d[parent_id]', '$datetime')";
			if(!mysql_query($sql)){
				$errmsg.="Error creating a category.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}else{
				$new_cid=mysql_insert_id();
			}
			if(!$errmsg){
				$msg=replace_tag(__("The category '<%cat%>' has been successfully created."), array("<%cat%>"=>$post_h["_title"]))."<br />\n";
			}
		}else{//update
			$sql="update $db->product_category set title='$post_d[_title]', parent_id='$post_d[parent_id]' where id='$get_d[id]' limit 1";
			if(!mysql_query($sql)){
				$errmsg.="Error updating the category.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}
			if(!$errmsg){
				$msg=replace_tag(__("The category '<%cat%>' has been successfully updated."), array("<%cat%>"=>$post_h["_title"]))."<br />\n";
			}
		}

		if($errmsg){
			$critical_error=$errmsg;
		}else{
			$cats=get_all_subcat_by_maincat();
			for($i=0,$t=count($cats);$i<$t;$i++){
				$r_cat[($i+1)]=$cats[$i]["id"];
				$r_cat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
			}
		}
	}

	//log critical error
	if($critical_error){
		$error_type_code=$_GET["type"]=="add"? "a-ca" : "a-ce";
		$affected_uid=0;
		log_activity('e', 'a', $aid, 'n', $affected_uid, $error_type_code, $critical_error);
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err("There is some error(s), please correct them before continuing:<br />\n<br />\n$errmsg") : "";
}
//#####END CATEGORY POST#####

$form_fields=array("_title"=>"","parent_id"=>"0");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=(!$posting? ($_GET["type"]=="edit"? $r_cat[$db_fieldname] : $default) : $post_h[$field]);
}
$parent_id_select=build_select($r_cat, $r_cat_d, $dis["parent_id"], "parent_id", $inputbox_style);

//javascript
ob_start();
?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
jQuery(document).ready(function(j){
 j('form[@name=cat_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });
});
</script>
<?php
$jvscript = ob_get_clean();

//back button
$url_referer=$_SERVER["HTTP_REFERER"];
if($post_s["back_url"]){
	$back_url=$post_s["back_url"];
}elseif($url_referer && !strstr($url_referer, $this_file)){
	$back_url=$url_referer;
}else{
	$back_url=$list_cat_file;
}

$display_fields=array("_title");
foreach($form_fields as $field => $default){
	if(in_array($field, $display_fields)){
		$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
		$dbr=explode("#", $vars["dbr"]["product_category"][$db_fieldname]);
		$readonly=$textarea=false;
		$readonly_str=$readonly? "readonly='readonly'" : "";
		$form_inputfield[$db_fieldname]="
		<tr>
			<td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
			<td>".($textarea? "<textarea name='$field' rows='12' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
			<input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
		</tr>";
	}
}

$cat=($errmsg || $msg?
"$errmsg $msg" : "")."
<form name='cat_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='back_url' value=\"$back_url\" />
<table class='amt_table'>
	<tr class='amt_header'>
		<td colspan='2'>".__("Category Information")."</td>
	</tr>".($_GET["type"]=="edit"? "
	<tr>
		<td width='$td_width'>".__("Category ID").__(":")."</td>
		<td>$get_s[id]</td>
	</tr>" : "")."
	$form_inputfield[title]
	<tr>
		<td>".__("Parent Category").__(":")." ".__("*")."</td>
		<td>$parent_id_select</td>
	</tr>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='button' value='".__("Back")."' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
		<input type='submit' name='submit_btn' value=\"".__(($_GET["type"]=="edit"? "Update" : "Add")." Category")."\" />
		</td>
	</tr>
</table>";

$content="<h2>$page_title</h2>$cat";

print format_admin_page($content, $this_title, $jvscript);
?>